#include <MultiplexD/WorkerModel/MultiplexWorker.h>

#include <Ape/EIndexOutOfRange.h>
#include <Ape/Collections/StringList.h>

#include <MultiplexD/DaemonInstance.h>

namespace MultiplexD {
	namespace WorkerModel {
		MultiplexWorker::MultiplexWorker() 
				: m_DoIgnoreExceptions(false)
		{}
		MultiplexWorker::~MultiplexWorker() {}
		
		void MultiplexWorker::HandleError(Ape::Exception& exc) {
			if (!m_DoIgnoreExceptions) {
				ERROR(exc.ToString() + Ape::IO::NewLine +
						L"\t\t" + exc.get_StackTrace().Join(Ape::IO::NewLine).Replace(L"\n", L"\n\t\t") +
						Ape::IO::NewLine +
						L"----------------------------------------------------------------------------"
					);
			}
			else {
				exc._Dump();
			}
		}
		
		MultiplexWorker* MultiplexWorker::Find(const Ape::Uuid& id) {
			Ape::MT::Thread* thr = NULL;
			try {
				thr = Ape::MT::Thread::ByID(id);
			}
			catch (Ape::EIndexOutOfRange& exc) {
				throw Ape::EIndexOutOfRange(L"No worker with the specified id: " + id.ToString());
			}
			MultiplexWorker* worker = NULL;
			try {
				worker = dynamic_cast<MultiplexWorker*>(thr);
			}
			catch (...) {
				worker = NULL;
			}
			if (worker)
				return worker;
			
			throw Ape::EIndexOutOfRange(L"No worker with the specified id: " + id.ToString());
		}
	}
}
